import { Box3Get, Box3Put, escapeHtml } from "@ap/util/request";
import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { auth } from "@ap/util/request";
import { updatePackageJson, getPackageJson } from "@ap/util/packageJson";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import { CommandId, playerSkinMap } from "@ap/command";
import insertCode from "@ap/util/vscode/insertCode";
import { PackageConfig } from "@ap/types/config";
import openInternetImage from "@ap/webView/img";

/**
 * 物品接口，扩展了共享的物品属性，添加了描述和ID。
 */
interface Item {
  modelName: string;
  modelDescription: string;
  modelPreviewUrl: string;
  modelId: string;
}

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  modelId: string;
  view: string;
}

/**
 * 异步获取地图玩家皮肤列表数组。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function getPlayerSkinMapList(): Promise<
  ExtendedQuickPickItem[] | undefined
> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const requestOptions = {
          url:
            "models/v2?modelType=3&mapId=" +
            mapId +
            "&creativeMode=2&containerMode=edit&orderBy=2",
        };
        /**
         * 发送请求并等待响应。
         */
        const response = await Box3Get(requestOptions, "地图玩家皮肤");
        /**
         * 检查响应是否成功，如果不成功则返回错误消息。
         */
        if (!response || response.code !== 200) {
          showErrorMessage(`获取地图玩家皮肤数据失败: ${response?.code}`);
          return;
        }
        /**+
         * 处理响应数据，映射物品到数据项格式，并转义HTML字符以防止XSS攻击。
         */
        const dataSource: ExtendedQuickPickItem[] = response.data.rows.map(
          (item: Item) => ({
            label: `${item.modelName}`,
            description: `${item.modelDescription.toString()}`,
            view: item.modelPreviewUrl,
            modelId: item.modelId.toString(),
          }),
        );
        playerSkinMap.description = `共${dataSource.length}项`;
        return dataSource;
      }
    }
  });
}
